<template>
  <div class="mateial_account">
    <div class="add_btn_top">
      <el-button
        icon="el-icon-plus"
        type="primary"
        size="mini"
        @click="handleAdd"
        >添加</el-button
      >
      <el-button class="button" size="mini" @click="handleImport">
        <svg-icon class="svg-icon" icon-class="import" />导入
      </el-button>
      <el-button class="button" size="mini" @click="handleExport">
        <svg-icon class="svg-icon" icon-class="import" />导出
      </el-button>
      <el-button class="button" size="mini">
        <svg-icon class="svg-icon" icon-class="import" />第三方系统集成
      </el-button>
      <!-- <el-button type="primary" size="mini">导入</el-button>
      <el-button type="primary" size="mini">第三方集成</el-button> -->
      <el-button
        icon="el-icon-arrow-down"
        type="primary"
        size="mini"
        @click="handleAddSubmit"
        >发送</el-button
      >
      <div style="margin: 0 10px" :style="{ color: switchTextColor }">
        {{ switchText }}
      </div>
      <el-switch v-model="screen" class="screenSwitch" active-color="#2680D2" />
    </div>
    <el-container>
      <!--  -->
      <el-main style="padding: 0; background: #fff">
        <div style="width:100%;" class="flex-x flex-center">
          <el-tabs v-model="activeName" @tab-click="handleClick" stretch>
            <el-tab-pane
              v-for="item in manufactureSiteList"
              :key="item.token"
              :label="item.name"
              :name="item.name"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <div class="w100">
          <el-table
            ref="multipleTable"
            v-adaptive
            :row-class-name="tableRowClassName"
            height="100px"
            style="width: 100%"
            :data="tableData"
            border
            row-key="id"
            size="small"
            @selection-change="handleSelectionChange"
          >
            <template v-for="(item, index) in getColumnList">
              <el-table-column
                v-if="item.type === 'selection'"
                :key="index"
                :show-overflow-tooltip="true"
                :minWidth="item.width"
                :reserve-selection="true"
                :selectable="selectable"
                align="center"
                :type="item.type"
              />
              <el-table-column
                v-else-if="item.type === 'formula'"
                :key="index"
                :show-overflow-tooltip="true"
                :width="item.width"
                :prop="item.prop"
                :label="item.label"
                align="center"
                :type="item.type"
              >
                <template slot-scope="props">
                  <el-popover placement="bottom" width="800" trigger="click">
                    <div style="width: 100%">
                      <el-table
                        v-if="
                          props.row.formula &&
                            props.row.formula.formulaParameter.length
                        "
                        max-height="500px"
                        min-height="100%"
                        border
                        size="mini"
                        :data="props.row.formula.formulaParameter"
                        style="width: 100%"
                      >
                        <el-table-column
                          v-for="(item, index) in props.row.formula
                            .formulaParameter[0].keys"
                          :label="item"
                          :key="index"
                          align="center"
                        >
                          <template slot-scope="scope">
                            {{ scope.row.values[index] }}
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <el-button slot="reference" type="text">查看工艺</el-button>
                  </el-popover>
                </template>
              </el-table-column>
              <template v-else>
                <el-table-column
                  v-if="isTabShow(item.label)"
                  :key="index"
                  :show-overflow-tooltip="true"
                  sortable
                  :width="item.width"
                  :prop="item.prop"
                  :label="item.label"
                  align="center"
                  :type="item.type"
                />
              </template>
            </template>
            <el-table-column
              prop="createdDate"
              label="创建时间"
              align="center"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.createdDate | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              prop="updatedDate"
              label="更新时间"
              width="180"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.updatedDate | formatDate }}
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              fixed="right"
              label="操作"
              width="120px"
              align="center"
            >
              <!-- eslint-disable-next-line -->
              <template slot="header" slot-scope="scope">
                <div class="flex-x flex-space" style="padding: 0 10px">
                  <div>操作</div>
                  <el-popover width="100" trigger="click">
                    <div class="column_search_box">
                      <div class="column_title">自定义表头字段</div>
                      <el-checkbox-group v-model="colCheckList">
                        <div class="flex-y column_search">
                          <el-checkbox
                            v-for="item in getColumnCheckList"
                            :key="item.label"
                            :label="item.label"
                          >
                            {{ item.label }}</el-checkbox
                          >
                        </div>
                      </el-checkbox-group>
                    </div>
                    <span slot="reference" class="el-icon-s-grid" />
                  </el-popover>
                </div>
              </template>

              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-edit-outline"
                  @click="handleEdit(scope.row)"
                />
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delAccount(scope.row)"
                />
                <el-button
                  type="text"
                  size="mini"
                  icon="el-icon-view"
                  @click="checkDetails(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            :total="total"
            :page.sync="pageNum"
            :limit.sync="pageSize"
            :page-sizes.sync="pageSizes"
            @pagination="pagination"
          />
        </div>
      </el-main>
      <el-aside
        v-show="screen"
        style="background: #fff; padding: 10px; margin-left: 10px"
        width="18%"
      >
        <Search
          :data-all="dataAll"
          :user-list="userList"
          @setFilterList="setFilterList"
        />
      </el-aside>
    </el-container>
    <AddDialog
      ref="detailsRef"
      :manufactureSite="activeName"
      :show-dialog.sync="showDialog"
      :list="templateList"
      :token="token"
      :isedit="isedit"
      @closeDialog="handleClose"
      :reportId="reportId"
      :templateId="templateId"
    />
    <DetailsDialog :show-dialog.sync="showDetailsDialog" :token="byId" />
    <!-- 导入 -->
    <ImportDialog
      :show-dialog.sync="showImportDialog"
      :templateId="templateId"
      :manufactureSite="activeName"
      @closeDialog="closeImportDialog"
    />
    <!-- 导出 -->
    <ExportDialog
      :show-dialog.sync="showExportDialog"
      :table-data="dataAll"
      :user-list="userList"
    />
  </div>
</template>

<script>
const COLUMN_LIST = [
  {
    label: "",
    prop: "",
    type: "selection",
    width: "55px",
    hideCheck: true // 不进行筛选
  },
  {
    label: "序号",
    prop: "",
    type: "index",
    width: "55px",
    hideCheck: true // 不进行筛选
  },
  {
    label: "工艺信息",
    prop: "",
    type: "formula",
    width: "150px",
    hideCheck: true // 不进行筛选
  },
  {
    label: "来件单位",
    prop: "unit",
    hideCheck: true,
    width: "150px"
  },
  // {
  //   label: "制造单元",
  //   prop: "manufactureSite",
  //   width: "150px"
  // },
  {
    label: "型别",
    prop: "model",
    width: "150px"
  },
  {
    label: "批次号",
    prop: "batchNumber",
    width: "150px"
  },
  {
    label: "零件号",
    prop: "partNumber",
    width: "150px"
  },
  {
    label: "零件名称",
    prop: "partName",
    width: "150px"
  },
  {
    label: "委托工序号",
    prop: "entrustProcessNumber",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "委托工序名称",
    prop: "entrustProcessName",
    width: "150px",
    showoverflowtooltip: true
  },
  {
    label: "工序/工步号",
    prop: "processNumber",
    width: "150px"
  },
  {
    label: "工序/工步名称",
    prop: "processName",
    width: "150px"
  },

  {
    label: "材料牌号",
    prop: "materialMark",
    width: "150px"
  },
  {
    label: "主制批次号",
    prop: "masterBatchNumber",
    width: "150px"
  },
  {
    label: "主制顺序号",
    prop: "masterOrderNumber",
    width: "150px"
  },
  //new
  {
    label: "发出部门编号",
    prop: "sendDepartmentNumber",
    width: "150px"
  },
  {
    label: "发出部门名称",
    prop: "sendDepartmentName",
    width: "150px"
  },
  //end
  {
    label: "接收部门编码",
    prop: "receiveDepartmentNumber",
    width: "150px"
  },
  {
    label: "接收部门",
    prop: "receiveDepartmentName",
    width: "150px"
  },
  {
    label: "来件数量",
    prop: "partTotalCount",
    width: "150px"
  },
  {
    label: "状态",
    prop: "state",
    width: "150px"
  },
  //new
  {
    label: "产品类别",
    prop: "productCategory",
    width: "150px"
  }

  // {
  //   label: "配方ID",
  //   prop: "formulaId",
  //   width: "150px"
  // },
  // {
  //   label: "资产台账编号",
  //   prop: "token",
  //   width: "150px"
  // }
];
import { mapGetters } from "vuex";
import Pagination from "@/views/common/page";
import AddDialog from "./components/AddDialog.vue";
import Search from "./components/searchFilter.vue";
import ImportDialog from "./components/ImportDialog.vue";
import ExportDialog from "./components/ExportDialog.vue";
import { getUserList } from "@/api/userAuth";
import {
  getAccount,
  putAccount,
  delAccount,
  submitAccount
} from "@/api/productionAccount";
import DetailsDialog from "./components/DetailsDialog.vue";
import { currentDate } from "@/utils/currentDate";
import { getTemplate } from "@/api/technology";

export default {
  components: {
    ExportDialog,
    ImportDialog,
    Pagination,
    AddDialog,
    Search,
    DetailsDialog
  },
  data() {
    return {
      activeName: "",
      activeToken: "",
      dataAll: [],
      showExportDialog: false,
      showImportDialog: false,
      showDetailsDialog: false,
      colCheckList: COLUMN_LIST.map(item => item.label),
      screen: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      tableData: [],
      pageNum: 1,
      pageSize: 20,
      pageSizes: [20, 50, 100, 300],
      total: 0,
      showDialog: false,
      userList: [],
      templateList: [],
      token: "",
      byId: "",
      isedit: false,
      multipleSelection: [],
      searchParams: {},
      reportId: "", //对应模板reportId
      templateId: "" //模板templateId
    };
  },
  computed: {
    ...mapGetters(["manufactureSiteList"]),
    formatState() {
      return function(data) {
        if (data == "true") {
          return "可用";
        } else if (data == "false") {
          return "禁用";
        }
      };
    },
    getColumnList() {
      return COLUMN_LIST;
    },
    getColumnCheckList() {
      return COLUMN_LIST.filter(item => !item.hideCheck);
    },
    isTabShow() {
      return function(name) {
        return this.colCheckList.includes(name);
      };
    }
  },
  async mounted() {
    this.activeName = this.manufactureSiteList[0].name;
    this.activeToken = this.manufactureSiteList[0].token;
    getAccount({
      page: 1,
      pageSize: 0
    }).then(res => {
      this.dataAll = res.data.results;
    });
    getUserList().then(res => {
      const { data } = res.data;
      this.userList = data;
    });
    this.getTemplates();
    this.init();
    getTemplate({
      page: 1,
      pageSize: 100,
      manufactureSite: this.activeName
    }).then(r => {
      const { data } = r;
      this.reportId =
        data.results && data.results.length ? data.results[0].token : "";
      this.templateId =
        data.results && data.results.length ? data.results[0].id : "";
    });
  },
  methods: {
    handleClick(e) {
      this.init();
      this.activeToken = this.manufactureSiteList[e.index].token;
      getTemplate({
        page: 1,
        pageSize: 100,
        manufactureSite: this.activeName
      }).then(r => {
        const { data } = r;
        this.reportId =
          data.results && data.results.length ? data.results[0].token : "";
        this.templateId =
          data.results && data.results.length ? data.results[0].id : "";
      });
    },
    // table颜色
    tableRowClassName({ row }) {
      const isversion = row.state == "未就绪";
      return isversion ? `row_color` : "";
    },
    closeImportDialog(isRefresh) {
      if (isRefresh) {
        this.init();
      }
    },
    // 导出
    handleExport() {
      this.showExportDialog = true;
    },
    // 导入
    handleImport() {
      if (this.templateId) {
        this.showImportDialog = true;
      } else {
        this.$msg({
          type: "warning",
          message: "当前制造单元无工艺基础信息"
        });
      }
    },
    checkDetails(row) {
      this.showDetailsDialog = true;
      this.byId = row.id;
    },
    selectable(row) {
      // 就绪 可以发送
      return row.state === "就绪";
    },
    async handleAddSubmit() {
      if (this.multipleSelection.length) {
        // const isversion = this.multipleSelection.every((item) => {
        //   return (
        //     item.stepInfoList.length &&
        //     item.stepInfoList.every((f) => f.version)
        //   );
        // });
        // if (!isversion) {
        //   this.$msg("请配置工艺版次!");
        //   return;
        // }
        // console.log("isversion :>> ", this.multipleSelection);
        // console.log("isversion :>> ", isversion);
        this.$confirm(
          `当前选中 ${this.multipleSelection.length} 个任务,是否确认发送至生产任务管理?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(async () => {
            const taskIdList = this.multipleSelection.map(item => item.id);
            await submitAccount({
              taskIdList,
              submitType: "发送",
              metadata: {},
              token: ""
            });

            this.$msg({
              type: "success",
              message: "发送成功"
            });
            this.$router.push({
              path: "/productionTask/receive-task/list",
              query: {
                activeName: this.activeName
              }
            });
            // this.init();
          })
          .catch(err => {});
      } else {
        this.$msg("请选择物料收发台账");
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      // this.select_number = this.multipleSelection.length;
      // this.select_Id = [];
      // if (rows) {
      //   rows.forEach((row) => {
      //     if (row) {
      //       this.select_Id.push(row.id);
      //     }
      //   });
      // }
    },
    versionServe(row, infoList) {
      const isVersion = infoList.every(item => item.version);
      if (!isVersion) {
        this.$msg("请选择版本号!");
        return;
      }

      const stepInfoList = infoList.map(item => {
        return {
          formulaId: item.formulaId,
          stepNumber: item.stepNumber,
          stepName: item.stepName,
          version: item.version
        };
      });
      putAccount(
        {
          ...row,
          stepInfoList
        },
        row.token
      ).then(res => {
        this.init();
        this.multipleSelection = [];
        this.$msg({
          type: "success",
          message: "保存成功"
        });
      });
    },
    stepVersion(val, row) {
      const obj = row.child.find(item => item.version == val);
      row.formulaId = obj.id;
      row.formulaParameter = obj.formulaParameter;
      row.state = obj.state;
      row.author = obj.author;
      row.createdDate = obj.createdDate;
      row.endDate = obj.endDate;
    },
    arraySpanMethod(row, column, rowIndex, columnIndex, arr) {
      if (columnIndex === 7) {
        if (rowIndex == 0) {
          return {
            rowspan: arr.length,
            colspan: 1
          };
        } else {
          // 不需要合并的还原,否则会错位
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    setFilterList(data) {
      if (data) {
        this.switchTextColor = "#2680D2";
        this.switchText = "显示筛选 ( 已筛选 )";
      } else {
        this.switchTextColor = "#666666";
        this.switchText = "显示筛选";
      }
      this.searchParams = data;
      this.init();
    },
    handleEdit(row) {
      this.isedit = true;
      this.token = row.token;
      this.showDialog = true;
      // getDetails(row.id).then((res) => {
      //   this.isedit = true;
      //   THIS.token = row.token
      //   console.log("res.data :>> ", res.data);
      //   this.showDialog = true;
      //   // this.$nextTick(() => {
      //   //   this.$refs.detailsRef.productionForm = res.data;
      //   // });
      // });
    },
    delAccount(row) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delAccount(row.token);
        this.$msg({
          type: "success",
          message: "删除成功!"
        });
        this.init();
      });
    },

    handleClose(isRefresh) {
      if (isRefresh) {
        this.init();
      }
      this.templateList = this.templateList.map(item => {
        return {
          ...item,
          checkList1: [],
          checkList2: []
        };
      });
      this.showDialog = false;
    },
    handleAdd() {
      if (this.templateId) {
        this.showDialog = true;
        this.isedit = false;
      } else {
        this.$msg({
          type: "warning",
          message: "当前制造单元无工艺基础信息"
        });
      }
    },
    init(data) {
      // qs.stringify(obj)
      getAccount({
        manufactureSite: this.activeName,
        page: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
        includeFormula: true,
        stateList:
          this.searchParams && this.searchParams.stateList
            ? this.searchParams.stateList
            : ["未就绪", "就绪"]
        // startDate: data && data.startDate ? data.startDate : currentDate(),
      }).then(res => {
        this.tableData = [];
        this.total = res.data.numResults;
        // res.data.results.forEach((ele, index) => {
        //   let dataInfo = {};
        //   ele.formulas.forEach((item) => {
        //     const stepObj = ele.stepInfoList.find(
        //       (s) => s.version == item.version && s.formulaId == item.id
        //     );
        //     let { stepNumber, stepName } = item;
        //     if (!dataInfo[stepNumber]) {
        //       dataInfo[stepNumber] = {
        //         stepNumber,
        //         stepName,
        //         state: stepObj ? item.state : "",
        //         author: stepObj ? item.author : "",
        //         createdDate: stepObj ? item.createdDate : undefined,
        //         endDate: stepObj ? item.endDate : undefined,
        //         version: stepObj ? stepObj.version : "",
        //         formulaId: stepObj ? stepObj.formulaId : "",
        //         formulaParameter: stepObj ? item.formulaParameter : [],
        //         child: [],
        //         show: false,
        //       };
        //     }
        //     dataInfo[stepNumber].child.push(item);
        //   });
        //   ele.formulas = Object.values(dataInfo);
        //   if (ele.stepInfoList.length) {
        //   }
        // });
        this.tableData = res.data.results;
        this.multipleSelection = [];
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
        });
      });
    },
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.init();
    },
    getTemplates(checkList1 = [], checkList2 = []) {
      getTemplate({
        page: 1,
        pageSize: 100
      })
        .then(r => {
          const { data } = r;
          // data.results = data.results.filter((item) => item.state == "true");
          data.results.map(item => {
            if (!item.checkList1) {
              item.checkList1 = [];
            }
            if (!item.checkList2) {
              item.checkList2 = [];
            }
            if (checkList1.length) {
              checkList1.forEach(t => {
                if (t.templateId == item.id) {
                  item.checkList1.push(Number(t.index));
                }
              });
            }
            if (checkList2.length) {
              checkList2.forEach(t => {
                if (t.templateId == item.id) {
                  if (!item.checkList2) {
                    item.checkList2 = [];
                  }
                  item.checkList2.push(Number(t.index));
                }
              });
            } else {
              item.checkList2 = [];
            }
          });
          this.templateList = data.results;
        })
        .finally(f => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.mateial_account {
  /deep/ .el-table__expanded-cell {
    padding: 16px 30px !important;
  }

  /deep/ .el-table {
    .row_color {
      background: #e4e7ed;
    }

    .el-table__body tr.hover-row.current-row > td,
    .el-table__body tr.hover-row.el-table__row--striped.current-row > td,
    .el-table__body tr.hover-row.el-table__row--striped > td,
    .el-table__body tr.hover-row > td {
      background-color: transparent;
    }

    tr:hover > td {
      background-color: transparent !important;
    }
  }
}
</style>
